package com.party.admin.web.controller.charge;

import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.charge.PackagePrivilege;
import com.party.core.model.charge.ProductPrivilege;
import com.party.core.service.charge.IPackagePrivilegeService;
import com.party.core.service.charge.IPackageService;
import com.party.core.service.charge.IPrivilegeService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 产品权限
 *
 * @author Administrator
 */
@Controller()
@RequestMapping("/charge/privilege")
public class ProdPrivilegeController {

    @Autowired
    private IPrivilegeService privilegeService;
    @Autowired
    private IPackagePrivilegeService packagePrivilegeService;
    @Autowired
    private IPackageService packageService;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 列表
     *
     * @param privilege
     * @param commonInput
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(ProductPrivilege privilege, CommonInput commonInput, Page page) {
        page.setLimit(20);
        privilege.setParentId("0");
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<ProductPrivilege> privileges = privilegeService.webListPage(privilege, params, page);

        ModelAndView mv = new ModelAndView("charge/privilege/privilegeList");
        mv.addObject("privileges", privileges);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 表单
     *
     * @param id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String id, String parentId) {
        ModelAndView mv = new ModelAndView("charge/privilege/privilegeForm");
        if (StringUtils.isNotEmpty(id)) {
            ProductPrivilege privilege = privilegeService.get(id);
            mv.addObject("privilege", privilege);
        }
        if (StringUtils.isEmpty(parentId)) {
            ProductPrivilege productPrivilege = new ProductPrivilege("0");
            productPrivilege.setName("根目录");
            mv.addObject("parentPrivilege", productPrivilege);
        } else {
            ProductPrivilege privilege = privilegeService.get(parentId);
            mv.addObject("parentPrivilege", privilege);
        }
        return mv;
    }

    /**
     * 保存
     *
     * @param privilege
     * @param result
     * @return
     */
    @ResponseBody
    @RequestMapping("save")
    public AjaxResult save(ProductPrivilege privilege, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            if (StringUtils.isEmpty(privilege.getParentId())) {
                privilege.setParentId("0");
                privilege.setParentIds("0");
            } else {
                ProductPrivilege parentHelp = privilegeService.get(privilege.getParentId());
                privilege.setParentIds(parentHelp.getParentIds() + "," + privilege.getParentId());
            }

            if (StringUtils.isEmpty(privilege.getId())) {
                String memberId = RealmUtils.getCurrentUser().getId();
                privilege.setCreateBy(memberId);
                privilege.setUpdateBy(memberId);
                privilegeService.insert(privilege);
            } else {
                ProductPrivilege dbHelp = privilegeService.get(privilege.getId());
                MyBeanUtils.copyBeanNotNull2Bean(privilege, dbHelp);
                privilegeService.update(dbHelp);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存产品权限异常", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("主键不能为空");
        }
        try {
            List<ProductPrivilege> privileges = privilegeService.list(new ProductPrivilege(id));
            List<PackagePrivilege> packagePrivileges = packagePrivilegeService.list(new PackagePrivilege("", id));
            if (packagePrivileges.size() > 0) {
                return AjaxResult.error("该权限已被分配，不能删除");
            }
            if (privileges.size() > 0) {
                return AjaxResult.error("该权限下已有子级权限，不能删除");
            }
            privilegeService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除权限异常{}", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 选择父级
     *
     * @param parentId
     * @return
     */
    @RequestMapping("{parentId}/selectParent")
    public ModelAndView selectParent(@PathVariable("parentId") String parentId) {
        ProductPrivilege parentHelp = new ProductPrivilege();
        parentHelp.setId("0");
        parentHelp.setName("根目录");
        List<ProductPrivilege> privileges = privilegeService.list(new ProductPrivilege("0"));
        privileges.add(0, parentHelp);
        ModelAndView mv = new ModelAndView("charge/privilege/selectParent");
        mv.addObject("privileges", privileges);
        mv.addObject("parentId", parentId);
        return mv;
    }

    /**
     * 根据父类找子类
     *
     * @param parentId
     * @return
     */
    @ResponseBody
    @RequestMapping("findByParentId")
    public AjaxResult findByParentId(String parentId) {
        List<ProductPrivilege> privileges = privilegeService.list(new ProductPrivilege(parentId));
        return AjaxResult.success(privileges);
    }

    /**
     * 检查编码
     *
     * @param code
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("checkCode")
    public boolean checkCode(String code, String id) {
        if (StringUtils.isEmpty(code)) {
            return false;
        }

        List<ProductPrivilege> roles = privilegeService.checkCode(code, id);
        if (roles.size() > 0) {
            return false;
        }
        return true;
    }
}
